#include "StdUtil.h"
#include "../x2lib.h"

using namespace x2lib;

std::vector<std::string> StdUtil::Split(std::string str, std::string div)
{
	std::vector<std::string> vecStr;
	for (int i = 0, j = str.find(div.c_str(), 0);; j = str.find(div.c_str(), i))
	{
		if (j == std::string::npos)
		{
			vecStr.push_back(str.substr(i, str.length() - i));
			break;
		}
		else
		{
			vecStr.push_back(str.substr(i, j - i));
		}
		i = j + div.length();
	}
	return vecStr;
}

std::wstring StdUtil::AStr2WStr(const char *str)
{
	const std::string strA(str);
	const char* pStr = strA.c_str();
	int len = strA.length();

	// figure out how many wide characters we are going to get   
	int nChars = MultiByteToWideChar(CP_ACP, 0, pStr, len, NULL, 0);
	if (len == -1)
		--nChars;
	if (nChars == 0)
		return L"";

	// convert the narrow string to a wide string   
	// nb: slightly naughty to write directly into the string like this  
	std::wstring buf;
	buf.resize(nChars);
	::MultiByteToWideChar(CP_ACP, 0, pStr, len, const_cast<wchar_t*>(buf.c_str()), nChars);

	return buf;
}

std::string StdUtil::WStr2AStr(const wchar_t *str)
{
	const std::wstring strW(str);
	const wchar_t* pStr = strW.c_str();
	int len = strW.length();

	int nChars = WideCharToMultiByte(CP_ACP, 0, pStr, len, NULL, 0, NULL, NULL);
	if (len == -1)
		--nChars;
	if (nChars == 0)
		return "";

	// convert the wide string to a narrow string  
	// nb: slightly naughty to write directly into the string like this  
	std::string buf;
	buf.resize(nChars);
	WideCharToMultiByte(CP_ACP, 0, pStr, len, const_cast<char*>(buf.c_str()), nChars, NULL, NULL);
	return buf;
}

std::string StdUtil::Float2Str(float f, const char *format)
{
	char temp[MAX_PATH];
	return std::string(StrUtil::Float2Str(f, temp, MAX_PATH, format));
}

std::string StdUtil::Int2Str(int i, const char *format)
{
	char temp[MAX_PATH];
	return std::string(StrUtil::Int2Str(i, temp, MAX_PATH, format));
}

std::string StdUtil::UTF8ToGBK(const std::string& strUTF8)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
	unsigned short * wszGBK = (unsigned short *)malloc(sizeof(unsigned short)*(len + 1));
	memset(wszGBK, 0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)(strUTF8.c_str()), -1, (LPWSTR)wszGBK, len);
	len = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
	char *szGBK = (char*)malloc(sizeof(char)*(len + 1));
	memset(szGBK, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wszGBK, -1, szGBK, len, NULL, NULL);
	std::string strTemp(szGBK);
	free(szGBK);
	free(wszGBK);
	return strTemp;
}

